package org.hmh.leetcode.hashtable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class code49_medium {
    static class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            Map<HashMap<Character, Integer>, Integer> indexMap = new HashMap<>();
            List<List<String>> resultList = new ArrayList<>();
            List<HashMap<Character, Integer>> list = new ArrayList<>();
            for (String str : strs) {
                HashMap<Character, Integer> map = getMap(str);
                int index = getSame(map, list, indexMap);
                if (index == -1) {
                    list.add(map);
                    List<String> listItem = new ArrayList<>();
                    listItem.add(str);
                    resultList.add(listItem);
                    indexMap.put(map, list.size() - 1);
                }else{
                    resultList.get(index).add(str);
                }
            }
            return resultList;
        }

        public int getSame(HashMap<Character, Integer> map, List<HashMap<Character, Integer>> list, Map<HashMap<Character, Integer>, Integer> indexMap) {
            for (HashMap<Character, Integer> m : list) {
                if (isSame(m, map)) {
                    return indexMap.get(m);
                }
            }
            return -1;
        }

        public boolean isSame(HashMap<Character, Integer> a, HashMap<Character, Integer> b){
            if (a.size() != b.size()) {
                return false;
            }
            for (Map.Entry<Character, Integer> entry : a.entrySet()) {
                Integer bValue = b.get(entry.getKey());
                if (bValue==null || !entry.getValue().equals(bValue)) {
                    return false;
                }
            }
            return true;
        }

        public HashMap<Character, Integer> getMap(String string) {
            HashMap<Character, Integer> map = new HashMap<>();
            for (char c : string.toCharArray()) {
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
            return map;
        }
    }

    public static void main(String[] args){
        Solution solution = new Solution();
        System.out.println(solution.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
    }
}
